package service

import (
	"github.com/gofiber/fiber/v2"
	"guns-excel/internal/app/model"
	"guns-excel/internal/app/repository"
	"guns-excel/internal/pkg/database"
	"guns-excel/internal/pkg/util"
	"guns-excel/internal/pkg/util/result"
	"strconv"
	"time"
)

func AddTimedTask(ctx *fiber.Ctx, p *model.TimedTask) error {
	p.Id = util.GetId()
	nowDate := time.Now()
	p.CreatedOn = &nowDate
	return repository.AddTimedTask(ctx, p, database.MysqlDB)
}

// 定时任务列表
func TimedTaskPageList(ctx *fiber.Ctx, pager *result.Pager, task *model.TimedTask) (*result.PagerRes, error) {
	list, count, err := repository.TimedTaskPageList(ctx, pager, task, database.MysqlDB)
	if err != nil {
		return nil, err
	}
	return &result.PagerRes{
		PageIndex: pager.PageIndex,
		PageSize:  pager.PageSize,
		Count:     count,
		List:      list,
	}, nil
}

func TimedTaskList(ctx *fiber.Ctx, task *model.TimedTask) ([]*model.TimedTask, error) {
	return repository.TimedTaskList(ctx, task, database.MysqlDB)
}

func TimedUpdate(ctx *fiber.Ctx, task *model.TimedTask) error {
	values := map[string]interface{}{
		"modified_on": time.Now(),
	}
	if strconv.Itoa(int(task.JobId)) != "" {
		values["job_id"] = task.JobId
	}
	if strconv.Itoa(task.IsStart) != "" {
		values["is_start"] = task.IsStart
	}
	return repository.TimedUpdate(ctx, values, task, database.MysqlDB)
}
